const response = require('./internal/response');

let cloud;

'use strict';

class Router {
    #fixPrefix

    constructor(clu, fixPrefix = '') {
        cloud = clu
        this.#fixPrefix = fixPrefix !== '' ? fixPrefix + '/' : fixPrefix;
    }

    async process(event) {
        const {url, params} = event;
        const parts = url.split('/');
        const method = parts.splice(-1, 1);
        const handler = parts.splice(-1, 1);
        const middle = parts.join('/') + (parts.length ? '/' : '');
        const jsFile = '../functions/' + this.#fixPrefix + middle + handler;
        const target = require(jsFile);

        return await target.getInstance(event)[method](params);
    }
}

class RouteBase {
    static instance;
    cloud;
    db;
    _;
    $;
    wxContext;
    response;
    event;

    constructor(event = {}) {
        const {env} = event;
        cloud.init({
            env: env || cloud.DYNAMIC_CURRENT_ENV
        })
        this.cloud = cloud;
        this.db = cloud.database({
            throwOnNotFound: false
        });
        this._ = this.db.command;
        this.$ = this.db.command.aggregate;
        this.wxContext = cloud.getWXContext();
        this.response = response;
        this.event = event;
    }

    static getInstance(event = {}) {
        if (!this.instance) {
            this.instance = new this(event);
        }
        return this.instance;
    }
}

module.exports = {Router, RouteBase};